import { Server } from "http"
import { AddressInfo } from "net"
import { readFileSync } from "fs"
import { fileURLToPath } from "url"
import { dirname, join } from "path"
import { AddressObject } from "../../index.d.js"
import MIME_LIST from "#assets/mime.js"

/** 用于 esm 获取当前环境 dirname
 * @param importMeta import.meta 对象
 * @returns dirname
 */
export function getDirname(importMeta?: { url: string }): string {
  importMeta = importMeta || import.meta
  const __filename = fileURLToPath(importMeta.url)
  return dirname(__filename)
}

/** 获取当前监听的 server 端口地址
 *
 * @param server 服务器实例对象
 * @return 服务器监听地址
 */
export function useAddress(server: Server): AddressObject {
  const addressInfo = server.address() as AddressInfo | string
  if (typeof addressInfo === "string") {
    return { hostname: addressInfo }
  } else {
    const { address, port, family } = addressInfo
    return {
      port,
      family,
      hostname: address === "::" ? "127.0.0.1" : address
    }
  }
}

/** 基于根目录的绝对地址读取文件
 *
 * @param readDirname 用于读取的文件目录
 * @param filePath 文件地址
 * @returns Buffer | null
 */
export function readFile(readDirname: string, filePath: string): Buffer | null {
  try {
    return readFileSync(join(readDirname, filePath))
  } catch (err) {
    return null
  }
}

/** 根据 extname 获取对应的 MIME 类型
 * @param extname 后缀名
 * @return MIME类型
 */
export function getMIME(extname: string): string {
  const MIME = Object.keys(MIME_LIST).find(MIME => {
    return MIME_LIST[MIME].includes(extname)
  })

  return MIME || ""
}
